﻿using Aspose.Cells;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Xml.Linq;

namespace TranslateJHR.Models
{
    public class TranslateHelp
    {
        public static List<TranslateModel> translateModel = new List<TranslateModel>();
        public static List<FileModel> fileModels = new List<FileModel>();
        public static int successCount = 0;
        //csproj路径
        public static string csprolText = File.ReadAllText(@"F:\Code\X6\Best.Site\Best.Site\X6.Site.csproj");


        /// <summary>
        /// 初始化excel
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public bool InitializationExcel(HttpPostedFileBase file)
        {
            translateModel = null;
            translateModel = new List<TranslateModel>();
            try
            {
                Workbook workbook = new Workbook(file.InputStream);
                //遍历表
                foreach (Worksheet worksheet in workbook.Worksheets)
                {
                    Cells cells = worksheet.Cells;
                    Dictionary<string, int?> cloume = new Dictionary<string, int?>();
                    //遍历第一行
                    foreach (var item in cells.Rows[0])
                    {
                        cloume.Add((item as Cell)?.StringValue, (item as Cell)?.Column);
                    }
                    //表头不包含翻译表头不遍历此表
                    if (!cloume.Keys.Contains("CN") || !cloume.Keys.Contains("EN")) continue;
                    foreach (Row row in cells.Rows)
                    {
                        if (row.Index == 0 || row.IsBlank == true)//跳过表头与空行
                        {
                            continue;
                        }
                        translateModel.Add(new TranslateModel
                        {
                            chinese = row.GetCellOrNull(cloume.Where(_ => _.Key == "CN").Select(_ => _.Value).FirstOrDefault().Value)?.StringValue,
                            english = row.GetCellOrNull(cloume.Where(_ => _.Key == "EN").Select(_ => _.Value).FirstOrDefault().Value)?.StringValue
                        });
                    }
                }
            }
            catch (Exception)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 遍历文件夹
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public void TraversalFile(DirectoryInfo Dir)
        {
            try
            {
                foreach (DirectoryInfo d in Dir.GetDirectories())//查找子目录
                {
                    TraversalFile(d);
                }
                foreach (FileInfo f in Dir.GetFiles("*.cshtml")) //查找文件
                {
                    if (f.Name.Contains("_en"))
                    {
                        fileModels.Add(new FileModel
                        {
                            FullName = f.FullName,
                            DirectoryName = f.DirectoryName,
                            Name = f.Name
                        });
                    }
                }
                //foreach (FileInfo f in Dir.GetFiles("*.js"))//查找文件
                //{
                //    if (!f.Name.Contains("_en"))
                //    {
                //        fileModels.Add(new FileModel
                //        {
                //            FullName = f.FullName,
                //            DirectoryName = f.DirectoryName,
                //            Name = f.Name
                //        });
                //    }
                //}
            }
            catch (Exception)
            {
                return;
            }
        }

        /// <summary>
        /// 替换文本
        /// </summary>
        public void loopFile()
        {
            fileModels = fileModels.Distinct().ToList();
            successCount = 0;

            foreach (var m in TranslateHelp.fileModels)
            {
                //读取文件并替换中文字段
                string newText = ReplaceText(m.FullName);
                //写人修改完的文件
                writeText(newText, m.DirectoryName, m.Name);
                successCount++;
            }

            //ParallelOptions p = new ParallelOptions()
            //{
            //    MaxDegreeOfParallelism = 8

            //};
            //Parallel.ForEach(TranslateHelp.fileModels, p, m =>
            //{
            //    //读取文件并替换中文字段
            //    string newText = ReplaceText(m.FullName);
            //    //写人修改完的文件
            //    writeText(newText, m.DirectoryName, m.Name);
            //    successCount++;
            //   // ContainFileToCsproj(m.DirectoryName.Substring(m.DirectoryName.IndexOf("Areas")) + "\\" + m.Name.Insert(m.Name.LastIndexOf('.'), "_en"));
            //});
        }


        /// <summary>
        /// 读取文件并替换中文字段
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public string ReplaceText(string path)
        {
            //直接读取出字符串
            string text = System.IO.File.ReadAllText(@path);

            foreach (var item in TranslateHelp.translateModel)
            {
                text = cshtmlRepalce(text, item.chinese, item.english);
            }

            return text;
        }

        /// <summary>
        /// 根据正则替换chhtml中指定字符串为指定内容
        /// </summary>
        /// <param name="input">cshtml内容</param>
        /// <param name="searchText">搜索的内容</param>
        /// <param name="repalceText">替换的内容</param>
        /// <returns>替换后的结果</returns>
        public string cshtmlRepalce(string input, string searchText, string repalceText)
        {
            searchText = Regex.Replace(searchText, @"\[|\]|\.|\(|\)", @"\$0");
            Regex reg = new Regex(@"(?<![\u4e00-\u9fa5])" + searchText + @"(?![\u4e00-\u9fa5])");
            return reg.Replace(input, repalceText);
        }

        /// <summary>
        /// 写入翻译完的文件
        /// </summary>
        public void writeText(string newText, string path, string name)
        {
            //注释替换原件
            //int indexOF = name.LastIndexOf('.');
            //name = name.Insert(indexOF, "_en");
            File.WriteAllText(@path + "\\" + name, newText, Encoding.UTF8);
        }

        public static void ContainFileToCsproj(string fileName)
        {
            XDocument doc = XDocument.Parse(csprolText);
            XElement root = doc.Root;
            string xmlns = "{" + root.Attribute("xmlns").Value + "}";
            IEnumerable<XElement> compileList = root.Elements(xmlns + "ItemGroup").Elements(xmlns + "Content");
            XElement itemGroup = compileList.FirstOrDefault().Parent;
            if (compileList.Where(u => u.Attribute("Include").Value == fileName).Count() > 0)
            {
                compileList.Where(u => u.Attribute("Include").Value == fileName).Remove();
            }

            XElement compile = new XElement(xmlns + "Content");
            compile.SetAttributeValue("Include", fileName);
            itemGroup.AddFirst(compile);

            csprolText = doc.ToString();
        }

        public void writeCsproj(string path)
        {
            File.WriteAllText(@"C:\Users\jacak.yang\Desktop\X6.Site.csproj", csprolText, Encoding.UTF8);
        }
    }
}